import List, { IItemDraggingProps, ItemDragging } from "devextreme-react/list";
import React, { useCallback, useImperativeHandle, useRef } from "react";
import { useState } from "react";
import { SampleField, SampleTable } from "../typing";
import { DevPopup, LayoutB } from "~/public/cpas-ui";
import { msgError } from "@/utils/msg";

export const SortFieldsPopup = React.forwardRef((props: any, ref: any) => {
    /*  const { initialState } = useModel('@@initialState'); //打包后,要报错,不知道为什么 引用报错,需要这样 import { useModel } from "umi";
     const { dbname, sjnd } = initialState?.curPart as any; */
    const [visible, setVisible] = useState<boolean>(false);
    const popupRef = useRef<any>();
    const diaParams = useRef<any>()

    const [tableFieldArray, setTableFieldArray] = useState<SampleField[]>([]);
    const [sortFieldArray, setSortFieldArray] = useState<SampleField[]>([]);
    useImperativeHandle(ref, () => ({
        show: (params: any) => {
            diaParams.current = params;

            const sampleTable: SampleTable = params.sampleTable;
            const sampleSourceFields: SampleField[] = params.sampleSourceFields;
            setTableFieldArray(sampleSourceFields.filter(item => !sampleTable.sortFieldsArray.includes(item.fieldName)));

            const sortFieldArray: any[] = sampleTable.sortFieldsArray.map(fieldName => sampleSourceFields.find(item => item.fieldName == fieldName));
            setSortFieldArray(sortFieldArray);
            setVisible(true);
        },
    }));

    const onDragStart = useCallback<IItemDraggingProps['onDragStart']>((e: any) => {
        e.itemData = e.fromData === 'tableFields' ? tableFieldArray[e.fromIndex] : sortFieldArray[e.fromIndex];
    }, [tableFieldArray, sortFieldArray]);

    const onAdd = useCallback<IItemDraggingProps['onAdd']>((e: any) => {
        const fields = e.toData === 'tableFields' ? tableFieldArray : sortFieldArray;

        const updatedFields = [...fields];
        updatedFields.splice(e.toIndex, 0, e.itemData);

        if (e.toData === 'tableFields') {
            setTableFieldArray(updatedFields);
        } else {
            setSortFieldArray(updatedFields);
        }
    }, [setTableFieldArray, setSortFieldArray, tableFieldArray, sortFieldArray]);

    const onRemove = useCallback<IItemDraggingProps['onRemove']>((e: any) => {
        const fields = e.fromData === 'tableFields' ? tableFieldArray : sortFieldArray;
        const updatedFields = [...fields];
        updatedFields.splice(e.fromIndex, 1);

        if (e.fromData === 'tableFields') {
            setTableFieldArray(updatedFields);
        } else {
            setSortFieldArray(updatedFields);
        }
    }, [setTableFieldArray, setSortFieldArray, tableFieldArray, sortFieldArray]);

    const onReorder = useCallback((e: any) => {
        if (e.fromData === e.toData) {
            const updateFields = (fields: SampleField[]) => {
                const updatedFields = [...fields];
                const [movedTask] = updatedFields.splice(e.fromIndex, 1);
                updatedFields.splice(e.toIndex, 0, movedTask);
                return updatedFields;
            };

            if (e.fromData === 'tableFields') {
                setTableFieldArray((prevFields: SampleField[]) => updateFields(prevFields));
            } else {
                setSortFieldArray((prevFields: SampleField[]) => updateFields(prevFields));
            }
        }
        else {
            onRemove(e);
            onAdd(e);
        }
    }, [onAdd, onRemove]);
    return <DevPopup.Logic
        ref={popupRef}
        width={800}
        height={600}
        visible={visible}
        title={diaParams.current?.title}
        rtlEnabled={false}
        // toolbarDisplay={false}//不显示确定
        // okDisabled={loading}
        // okText={intl('ac.submitServer', '提交')}

        onCancel={() => { setVisible(false); }}
        onHiding={() => setVisible(false)}
        onOK={() => {

            if (sortFieldArray.length == 0) {
                return msgError('排序字段不能为空,请从左侧拖拽排序字段!')
            }
            diaParams.current.onOk && diaParams.current.onOk(sortFieldArray.map(item => item.fieldName))


        }}

    //  toolbarDisplay={false}
    >
        {() => {//必须用函数返回
            function leftContainer() {
                return <List
                    dataSource={tableFieldArray}
                    keyExpr="fiedName"
                    displayExpr="fieldTitle"
                    searchExpr={"fieldTitle"}
                    height={450}
                    searchMode={"contains"}
                    searchEnabled={true}
                    scrollingEnabled={true}
                    pageLoadMode='scrollBottom' //直接加载,不显示 更多
                    style={{ border: '1px solid gray' }}//加一个灰色边框
                    
                >
                    <ItemDragging
                        allowReordering={true}
                        group="fields"
                        data="tableFields"
                        onDragStart={onDragStart}
                        onAdd={onAdd}
                        onRemove={onRemove}
                        onReorder={onReorder}
                        >
                    </ItemDragging>
                    
                </List>
            }
            function rightContainer() {
                return <List
                    style={{ marginLeft: 20, border: '1px solid gray' }}//加一个灰色边框
                    dataSource={sortFieldArray}
                    keyExpr="fiedName"
                    displayExpr="fieldTitle"
                    searchExpr={"fieldTitle"}
                    height={450}
                    noDataText="从左侧拖拽字段到此处进行排序"
                    searchEnabled={true}
                    scrollingEnabled={true}
                    pageLoadMode='scrollBottom' //直接加载,不显示 更多
                >
                    <ItemDragging
                        allowReordering={true}
                        group="fields"
                        data="sortFields"
                        onDragStart={onDragStart}
                        onAdd={onAdd}
                        onRemove={onRemove}
                        onReorder={onReorder}>
                    </ItemDragging>
                </List>
            }
            return (<div className="">
                <LayoutB
                    rowSize={["350", "350px"]}
                    leftSlot={leftContainer()}
                    rightSlot={rightContainer()}
                />


            </div>

            )
        }}

    </DevPopup.Logic >



})